import { Component, HostListener, OnDestroy, OnInit } from "@angular/core";
import { CommService } from "../comm-service";
import { FormBuilder, FormGroup } from "@angular/forms";
import { SharedService } from "../shared-service";
import { sjgzxinModuledatas } from "../pubcomponent/pageTitle.datas";
import { bjlxKeyValue, bjlxList } from "../base-code";
import { MyValidator } from "../myvalidator-util";
import { MyhttpService } from "../myhttp.service";

declare var $: any;
declare var AMap: any;

@Component({
  template: `
  <div class="all_bg paddingTop">
    <div class="">
        <div class="marginBottom">
        <ng-container *ngIf="actionobj1.length">
          <portlet-action class="actions" [o]="actionobj1" (outhander)="actionHander($event)"></portlet-action>
        </ng-container>
        </div>
      <div class="portlet-body">
        <form class="form-horizontal" role="form" style="border-bottom: 1px solid #ccc;">
          <div class="row">
            <div class="col-lg-3">
              <div class="form-group">
                <label class="col-lg-3 control-label" for="bjlx">告警类型：</label>
                <div class="col-lg-9">
                  <select class="form-control" id="bjlx" name="bjlx" [(ngModel)]="s_obj.bjlx"></select>
                </div>
              </div>
            </div>
            <div class="col-lg-3">
              <div class="form-group">
                <label class="col-lg-4 control-label" for="bjxxbh">告警信息编号：</label>
                <div class="col-lg-8">
                  <input type="text" class="form-control" id="bjxxbh" name="bjxxbh" [(ngModel)]="s_obj.bjxxbh">
                </div>
              </div>
            </div>
            <div class="col-lg-6">
              <div class="form-group">
                <label class="col-lg-3 control-label">告警时间：</label>
                <div class="col-lg-9">
                  <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-calculator"></i></span>
                    <input type="text" class="form-control datetimepickerB_content" id="s_sbtimegj"
                           [value]="s_obj.kssj">
                    <span class="input-group-addon">至</span>
                    <input type="text" class="form-control datetimepickerE_content" id="s_edtimegj"
                           [value]="s_obj.jssj">
                    <span class="input-group-addon"><i class="fa fa-calculator"></i></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-lg-3">
              <div class="form-group">
                <label class="col-lg-3 control-label" for="clzt">处理状态:</label>
                <div class="col-lg-9">
                  <select class="form-control" id="clzt" name="clzt" [(ngModel)]="s_obj.clzt"></select>
                </div>
              </div>
            </div>
            <div class="col-lg-2">
              <div class="form-group">
                <button type="button" class="btn blue" (click)="inittable_gjxq()">
                  <i class="fa fa-search"></i> 搜索
                </button>
              </div>
            </div>
          </div>
        </form>
        <div class="row" style="margin-top: 10px">
          <div class="col-lg-12" *ngIf="table_gjxq">
            <my-table [o]="table_gjxq"></my-table>
          </div>
        </div>
      </div>
    </div>

    <div class="modal fade" id="gjhanderModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel2">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel2">告警处理</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <form class="form-horizontal" role="form" [formGroup]="formgroup_ggcl">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">
                      <require-label></require-label>
                      处理意见:</label>
                    <div class="col-lg-8">
                      <textarea class="form-control" rows="5" formControlName="clyj_gjCtr"></textarea>
                      <div
                        *ngIf="formgroup_ggcl.get('clyj_gjCtr').invalid&&formgroup_ggcl.get('clyj_gjCtr').dirty">
                          <span *ngIf="formgroup_ggcl.hasError('myrequire','clyj_gjCtr')">
                                <tool-tip [o]="formgroup_ggcl.getError('myrequire','clyj_gjCtr').msg"></tool-tip>
                          </span>
                      </div>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              取 消
            </button>
            <button type="button" class="btn btn-primary" (click)="handGj()">
              确定
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="modal fade" id="clyjModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel2">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel2">处理意见</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <form class="form-horizontal" role="form" [formGroup]="formgroup_ggcl">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">处理意见:</label>
                    <div class="col-lg-8">
                      <textarea readonly class="form-control" rows="5" [value]="xqobj.clyj"></textarea>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal">
              确定
            </button>
          </div>
        </div>
      </div>
    </div>
    </div>

  `,
  styles: []
})
export class TjbbGjxqComponent implements OnInit, OnDestroy {
  userinfo: any;
  actionobj1: any[] = [];
  sjb_btns: any[] = ["gjxq_clN"];
  sjb_c_btns: any[] = ["cl_gjxq", "xq_gjxq"];
  hascbtns: any[] = [];

  s_obj: any = {
    bjxxbh: "",
    kssj: "",
    jssj: "",
    bjlx: "",
    clzt: "",
  }
  clztList: any[] = [{
    code: "0",
    name: "未处理"
  }, {
    code: "1",
    name: "已处理"
  }];
  table_gjxq: any;
  geocoder: any;
  formgroup_ggcl: FormGroup;
  xqobj: any = {
    clyj: ""
  };
  caozuo_bjxxbhs: string[] = [];

  /**
   * 初始化按钮
   */
  initactions(): void {
    // this.commservice.getroleBtns(this.sjb_btns, this.sjb_c_btns, this.userinfo.nowroleid, "tablegjxq", (hasportbtns, hastablebtns) => {
    //   this.actionobj1 = hasportbtns;
    //   this.hascbtns = hastablebtns;
    // });

    this.commservice.getroleBtns_not_permissions(this.sjb_btns, this.sjb_c_btns, "table_sjbcrk", (hasportbtns, hastablebtns) => {
      this.actionobj1 = hasportbtns;
      this.hascbtns = hastablebtns;
    })
  }

  /**
   * 按钮的处理回调
   * @param e
   */
  actionHander(e: any): void {
    const fromv = e.pfrom;
    const actiontype = e.type;
    if (fromv === "tablegjxq") {
      if (actiontype === "clN") {
        // 批量处理
        const selectrows = $("#table_gjxq").bootstrapTable("getSelections");
        if (selectrows.length == 0) {
          this.commservice.myswal("warning", "请选择处理的告警数据", "", "ts", null);
          return;
        }
        this.caozuo_bjxxbhs = selectrows.map((row) => {
          return row.bjxxbh;
        });
        this.addclyj();
      }
    }
  }


  inittable_gjxq(): void {
    const that = this;
    this.s_obj.kssj = $("#s_sbtimegj").val() ? $("#s_sbtimegj").val() : this.s_obj.kssj;
    this.s_obj.jssj = $("#s_edtimegj").val() ? $("#s_edtimegj").val() : this.s_obj.jssj;
    this.table_gjxq = {
      tableid: "table_gjxq",
      url: "sjgz/zsymtjbb/bjxxlb",
      reqobj: this.s_obj,
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      total: "totalRows",
      rows: "tjbbbjxxList",
      columns: [{
        checkbox: true
      }, {
        title: "序号",
        field: "ordernum",
      }, {
        title: "设备名称",
        field: "kdmc",
        visible: false
      }, {
        title: "ID",
        field: "sbid",
      }, {
        title: "告警类型",
        field: "bjlx",
        formatter: function (v) {
          let str: string;
          if (v) {
            str = bjlxKeyValue[v] ? bjlxKeyValue[v] : "";
          }
          return str;
        }
      }, {
        title: "告警时间",
        field: "bjsj",
      }, {
        title: '告警信息',
        field: 'bjxx'
      }, {
        title: "告警地址",
        field: "bjxxbh",
        events: this.myevents,
        formatter: function (v, row) {
          const jdv = row.jd;
          const wdv = row.wd;
          let str: string = "";
          if (jdv && wdv) {
            if (v.indexOf("|") == -1) {
              str += "<span class='getAddress' style='cursor: pointer;text-decoration-line: underline;color: blue'>查看地址</span>";
            } else {
              str += v.substring(1);
            }
          }
          return str;
        }
      }, {
        title: "处理状态",
        field: "sfcl",
        formatter: function (v) {
          let str: string = "";
          that.clztList.forEach((obj) => {
            if (v && v == obj.code) {
              str = obj.name;
            }
          });
          return str;
        }
      }, {
        title: "操作",
        field: "caozuo",
        events: this.myevents,
        formatter: function (v, row) {
          const sfclv = row.sfcl;
          let str: string = "";
          if (that.hascbtns.indexOf("cl_gjxq") != -1) {
            if (sfclv == "0") {
              str += "<button type='button' class='btn btn-xs btn-info cl_gjxq'><i class='fa fa-hand-grab-o'></i> 处理</button>";
            }
          }
          if (that.hascbtns.indexOf("xq_gjxq") != -1) {
            if (sfclv == "1") {
              str += "<button type='button' class='btn btn-xs btn-info xq_yjjy'><i class='fa fa-search'></i> 处理详情</button>";
            }
          }

          return str;
        }
      }]
    };
    this.table_gjxq.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 100;
  }

  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .getAddress": function (e, value, row, index) {
      const jdv = row.jd;
      const wdv = row.wd;
      if (jdv && wdv) {
        this.getAddresss([jdv, wdv], (resp) => {
          const dzmc = resp.regeocode.formattedAddress;
          const Flagbit = "|";
          $("#table_gjxq").bootstrapTable("updateCell", { index: index, field: "bjxxbh", value: Flagbit + dzmc });
        });
      }
    }.bind(this),
    "click .cl_gjxq": function (e, value, row, index) {
      const bjxxbhv = row.bjxxbh;
      this.caozuo_bjxxbhs = [bjxxbhv];
      this.addclyj();

    }.bind(this),
    "click .xq_yjjy": function (e, value, row, index) {
      const clyjv = row.clyj;
      this.xqobj.clyj = clyjv;
      $("#clyjModal").modal({
        keyboard: true,
        backdrop: 'static'
      })
    }.bind(this)
  }

  getAddresss(lnglatXY: any, callback: Function): void {
    this.geocoder.getAddress(lnglatXY, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        callback(result);
      }
    });
  }


  createformgroup(): void {
    this.formgroup_ggcl = this.fb.group({
      clyj_gjCtr: ["", [this.myValidator.myrequired("必填项目")]]
    });
  }


  addclyj(): void {
    this.formgroup_ggcl.reset();
    $("#gjhanderModal").modal({
      keyboard: true,
      backdrop: false
    });
  }


  handGj(): void {
    if (!this.formgroup_ggcl) {
      const ctrols = this.formgroup_ggcl.controls;
      for (let path in ctrols) {
        ctrols[path].markAsDirty();
        ctrols[path].updateValueAndValidity();
      }
      return
    }
    const formgroupv = this.formgroup_ggcl.getRawValue();
    const clyjv = this.commservice.removeSpace(true, formgroupv.clyj_gjCtr);
    this.commservice.blockUI({
      boxed: true,
      message: "处理中...",
      zIndex: 10051,
      overlayColor: "#67809F"
    });
    const url = "sjgz/zsymtjbb/ccbjxx";
    this.itservice.kwPtPost(url, {
      bjxxbhList: this.caozuo_bjxxbhs,
      clyj: clyjv
    }).subscribe(resp => {
      this.commservice.handResponse("put", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            $("#gjhanderModal").modal("hide");
            this.commservice.myswal("success", resp, "", "ts", null);
            this.table_gjxq = Object.assign({}, this.table_gjxq);
          }
        }
      });
    });
  }

  /**
   * 处理搜索表格
   */
  createSearchForm(): void {
    $('.datetimepickerB_content').datetimepicker({
      autoclose: true,
      language: 'zh-CN',
      format: 'yyyy-mm-dd hh:ii:ss',
      pickerPosition: "bottom-left",
      minView: 0
    }).on("changeDate", function (ev) {
      const selectdate = ev.date.valueOf(); // 实际时间+ 8h
      // 结束时间不能小于开始时间,
      $(".datetimepickerE_content").datetimepicker("setStartDate", new Date(selectdate - 8 * 60 * 60 * 1000));
    });
    $('.datetimepickerE_content').datetimepicker({
      autoclose: true,
      language: 'zh-CN',
      format: 'yyyy-mm-dd hh:ii:ss',
      pickerPosition: "bottom-left",
      minView: 0
    }).on("changeDate", function (ev) {
      const selectdate = ev.date.valueOf(); // 实际时间+ 8h
      // 开始时间不能大于结束时间
      $(".datetimepickerB_content").datetimepicker("setEndDate", new Date(selectdate - 8 * 60 * 60 * 1000));
    });
    const initBdate = this.commservice.YMDHMS_get(Date.now() - 24 * 60 * 60 * 1000);
    const initEdate = this.commservice.YMDHMS_get(false);
    this.s_obj.kssj = initBdate;
    this.s_obj.jssj = initEdate;


    //告警类型
    $("#bjlx").empty();
    let str_bjlx: string = "<option value=''>--全部--</option>";
    bjlxList.forEach((obj) => {
      str_bjlx += "<option value='" + obj.code + "'>" + obj.name + "</option>";
    });
    $("#bjlx").append(str_bjlx);
    $("#bjlx").selectpicker({
      size: 10
    });
    this.s_obj.bjlx = ""; // 全部

    // 处理状态
    $("#clzt").empty();
    let str_clzt: string = "<option value=''>--全部--</option>";
    this.clztList.forEach((obj) => {
      str_clzt += "<option value='" + obj.code + "'>" + obj.name + "</option>";
    });
    $("#clzt").append(str_clzt);
    $("#clzt").selectpicker({
      size: 10
    });
    this.s_obj.clzt = ""; // 全部
  }

  initMap(): void {
    const that = this;
    AMap.plugin(['AMap.Geocoder'],
      function () {
        that.geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
      });
  }


  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      this.initactions(); //用户按钮权限
    });
  }

  constructor(private commservice: CommService,
    private sharedService: SharedService,
    private myValidator: MyValidator,
    private itservice: MyhttpService,
    private fb: FormBuilder) {

  }

  ngOnInit() {
    // this.sharedService.emitChange({
    //   actiontype: "sendggsl"
    // });
    this.getuserinfo();
    this.initMap();
    this.createSearchForm();
    this.inittable_gjxq();
    this.createformgroup();
  }

  ngOnDestroy() {

  }

}
